package cvi.com.reader.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cvi.com.reader.R;
import cvi.com.reader.activity.ActivityBrowser;
import cvi.com.reader.activity.GridDetailsActivity;
import cvi.com.reader.activity.PersonalActivity;
import cvi.com.reader.activity.PoetryCollectionAcitivity;
import cvi.com.reader.activity.PopularWorksActivity;
import cvi.com.reader.activity.RandomReadingActivity;
import cvi.com.reader.activity.TextBookActivity;
import cvi.com.reader.activity.WorksDetailsAcitivity2;
import cvi.com.reader.adapter.HomePageGridAdapter;
import cvi.com.reader.adapter.HomePageListAdapter;
import cvi.com.reader.base.BaseFragment;
import cvi.com.reader.bean.BannerBean;
import cvi.com.reader.bean.CategoriesBean;
import cvi.com.reader.bean.HomePageDataBean;
import cvi.com.reader.bean.HotBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.refresh.CustomRefreshFooter;
import cvi.com.reader.tool.refresh.CustomRefreshHeader;
import cvi.com.reader.widgets.MultiStateView;
import cvi.com.reader.widgets.MyGridView;
import cvi.com.reader.widgets.MyListView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by WP on 2020/7/21.
 * 首页
 */

public class HomePageFragment extends BaseFragment implements View.OnClickListener {
    @BindView(R.id.banner)
    ConvenientBanner banner;
    @BindView(R.id.search_icon)
    ImageView searchIcon;
    @BindView(R.id.search_edittext)
    EditText searchEdittext;
    @BindView(R.id.search)
    CardView search;
    @BindView(R.id.user_info)
    ImageView userInfo;
    @BindView(R.id.gridview)
    MyGridView gridview;
    @BindView(R.id.mylistview)
    MyListView mylistview;
    @BindView(R.id.more_hot)
    TextView moreHot;
    @BindView(R.id.smartRefreshLayout_home)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.stateView)
    MultiStateView stateView;
    @BindView(R.id.phoenix_cademy_rl)
    RelativeLayout phoenixCademyRl;
    //诗词大会，首页，课本，绘本，文学巨匠
    private List<CategoriesBean.RowsBean> rowsBeanList = new ArrayList<CategoriesBean.RowsBean>();
    //首页宫格数据包含热门数据
    private List<HomePageDataBean.RowsBean> homeList = new ArrayList<HomePageDataBean.RowsBean>();
    private List<CategoriesBean.RowsBean> gridleList=new ArrayList<>();
    //首页热门数据
    private List<HotBean.RowsBean> homeHotList = new ArrayList<HotBean.RowsBean>();
    private int has_children = -1;
    private int pid = -1;
    private HomePageGridAdapter homePageAdapter;
    private HomePageListAdapter homePageListAdapter;
    private int hotDataId = -1;
    private HomePageDataBean.RowsBean rowBean = null;
    private String[]name={"小学语文","小学英语","唐诗","宋词"};
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_homepage;
    }

    @Override
    protected boolean isBindEventBus() {
        return true;
    }

    @Override
    protected void initData() {
        //绑定生命周期,获取宫格数据
        NetWorkManager.getInstance().getNetWorkApiService().getHomePageData(pid).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        //拿到所有的宫格数据及热门接口id;宫格界面数据目前写死，不使用此接口数据展示仅用接口数据各宫格id进入二级界面。
                        getData(response);
                        smartRefreshLayout.finishRefresh(true);
                        stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                    }
                });
    }

    @Override
    protected void initView() {
        search.getBackground().setAlpha(71);
        stateView.getBackground().setAlpha(153);
        initSmartRefreshLayout();//下拉刷新
        userInfo.setOnClickListener(this);
        moreHot.setOnClickListener(this);
        phoenixCademyRl.setOnClickListener(this);
        //轮播图
        List<BannerBean> bannerBeanList = new ArrayList<>();
        BannerBean bannerBean1 = new BannerBean(R.mipmap.ic_banner_01);
        BannerBean bannerBean2 = new BannerBean(R.mipmap.ic_banner_02);
        BannerBean bannerBean3 = new BannerBean(R.mipmap.ic_banner_03);
        BannerBean bannerBean4 = new BannerBean(R.mipmap.ic_banner_04);
        BannerBean bannerBean5 = new BannerBean(R.mipmap.ic_banner_05);
        bannerBeanList.add(bannerBean1);
        bannerBeanList.add(bannerBean2);
        bannerBeanList.add(bannerBean3);
        bannerBeanList.add(bannerBean4);
        bannerBeanList.add(bannerBean5);
        banner.setPages(new CBViewHolderCreator() {
            @Override
            public ImageHolderView createHolder() {
                return new ImageHolderView();
            }
        }, bannerBeanList)
                .startTurning(5000)
                .setPageIndicator(new int[]{R.mipmap.ic_banner_n, R.mipmap.ic_banner_p})
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
        gridleList.clear();

        if (Hawk.contains("categoriesBeanList")) {
            rowsBeanList.clear();
            rowsBeanList = Hawk.get("categoriesBeanList");
        }
        for (int i=0;i<rowsBeanList.size();i++){
            for (int k=0;k<name.length;k++){

                if (name[k].equals(rowsBeanList.get(i).getName())){
                    upGridData(rowsBeanList.get(i));
                    Log.d("sdfsfsdf",rowsBeanList.get(i).getName());
                    gridleList.add(rowsBeanList.get(i));

                }
            }

        }
        Log.d("sdfsfsdf222",gridleList.size()+"  ");
        homePageAdapter = new HomePageGridAdapter(getActivity(), gridleList);
        gridview.setAdapter(homePageAdapter);
        homePageAdapter.notifyDataSetChanged();

        if (rowsBeanList != null) {
            for (int i = 0; i < rowsBeanList.size(); i++) {
                if ("首页".equals(rowsBeanList.get(i).getName())) {
                    pid = rowsBeanList.get(i).getId();
                    has_children = rowsBeanList.get(i).getHas_children();
                }
                if ("示范诵读".equals(rowsBeanList.get(i).getName())) {
                    rowBean = new HomePageDataBean.RowsBean();
                    rowBean.setName("名家示范");
                    rowBean.setId(rowsBeanList.get(i).getId());
                    rowBean.setIcon(R.mipmap.ic_gridview_06);
                }
            }
        }
        //宫格点击事件-二级界面
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Bundle bundle = null;
                CategoriesBean.RowsBean gridViewBean = (CategoriesBean.RowsBean) adapterView.getAdapter().getItem(i);
                Hawk.put("CategoriesBean",gridViewBean);
                Bundle  bundle1=new Bundle();
                bundle1.putString("getName",gridViewBean.getName());

                if (gridViewBean.getName().equals("小学语文")||gridViewBean.getName().equals("小学英语")){

                    go(TextBookActivity.class,bundle1);

                }else  if (gridViewBean.getName().equals("唐诗")||gridViewBean.getName().equals("宋词")){

                    go(PoetryCollectionAcitivity.class,bundle1);
                }

            }
        });
        searchEdittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    Bundle bundle = new Bundle();
                    bundle.putString("searchStr", searchEdittext.getText().toString().trim());
                    bundle.putInt("isRandom", 2);
                    go(RandomReadingActivity.class, bundle);
                    return true;
                }
                return false;
            }
        });
    }

    private void upGridData(CategoriesBean.RowsBean rowsBeans) {


            switch (rowsBeans.getName()) {
                case "小学语文":
                    rowsBeans.setIcon(R.mipmap.ic_gridview_02);

                    break;
                case "中华经典诵读":
                    rowsBeans.setName("中华经典");
                    rowsBeans.setIcon(R.mipmap.ic_gridview_03);

                    break;
                case "小学英语":
                    rowsBeans.setIcon(R.mipmap.ic_gridview_04);

                    break;
                case "初中语文":

                    rowsBeans.setIcon(R.mipmap.ic_gridview_05);

                    break;
                case "唐诗":
                    rowsBeans.setIcon(R.mipmap.ic_gridview_07);

                    break;
                case "宋词":
                    rowsBeans.setIcon(R.mipmap.ic_gridview_08);

                    break;

            }


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    public class ImageHolderView implements Holder<BannerBean> {
        private ImageView imageView;

        @Override
        public void UpdateUI(Context context, int position, BannerBean data) {
            Glide.with(getActivity()).load(data.getResId()).into(imageView);
        }

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            return imageView;
        }

    }

    private void getData(JSONObject response) {
        JSONArray array = response.getJSONArray("rows");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            HomePageDataBean.RowsBean rowsBean = (HomePageDataBean.RowsBean) JSONObject.toJavaObject(object, HomePageDataBean.RowsBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            homeList.add(rowsBean);
        }
        if (homeList != null) {
            getHotData(homeList);
        }
    }

    private void getHotData(List<HomePageDataBean.RowsBean> homeLists) {

        for (int i = 0; i < homeLists.size(); i++) {
            if ("hot".equals(homeLists.get(i).getFlag())) {
                hotDataId = homeLists.get(i).getId();//获取热门作品ID，跳转热门作品页面请求数据用的。
                //绑定生命周期
                NetWorkManager.getInstance().getNetWorkApiService().getHomePageHotData(homeLists.get(i).getId()).compose(this.<JSONObject>bindToLifecycle())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                            @Override
                            protected void onSuccess(JSONObject response) {
                                //获取热门数据
                                setHotData(response);
                            }
                        });
            } else {

            }
        }



        for (int i = 0; i < homeLists.size(); i++) {
            if ("热门朗读".equals(homeLists.get(i).getName())) {
                homeLists.remove(i);
            }
        }
        HomePageDataBean.RowsBean rowsBean = new HomePageDataBean.RowsBean();
        rowsBean.setName("随机朗读");
        rowsBean.setIcon(R.mipmap.ic_gridview_01);
        homeLists.add(0, rowsBean);
        if (rowBean != null) {
            homeLists.add(5, rowBean);
        }

        mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                HotBean.RowsBean rowsBean = (HotBean.RowsBean) adapterView.getAdapter().getItem(i);
                Intent intent = new Intent(getActivity(), WorksDetailsAcitivity2.class);
                startActivity(intent);
                Hawk.put("WorksDetails", rowsBean);
            }
        });
    }

    private void setHotData(JSONObject response) {
        JSONArray array = response.getJSONArray("rows");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            HotBean.RowsBean rowsBean = (HotBean.RowsBean) JSONObject.toJavaObject(object, HotBean.RowsBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            homeHotList.add(rowsBean);
        }
        if (homeHotList != null) {
            List<HotBean.RowsBean> hotRosList = new ArrayList<>();//临时存放前五个对象
            if (homeHotList.size() <= 5) {
                homePageListAdapter = new HomePageListAdapter(getActivity(), homeHotList);
            }
            if (homeHotList.size() > 5) {
                for (int i = 0; i < 5; i++) {
                    hotRosList.add(homeHotList.get(i));
                    homePageListAdapter = new HomePageListAdapter(getActivity(), hotRosList);
                }
            }
            mylistview.setAdapter(homePageListAdapter);
            homePageListAdapter.notifyDataSetChanged();
        }
    }

    //初始化下拉刷新控件
    private void initSmartRefreshLayout() {
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setRefreshHeader(new CustomRefreshHeader(getActivity()));
        smartRefreshLayout.setRefreshFooter(new CustomRefreshFooter(getActivity(), "加载中…"));
        smartRefreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        smartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //  presenter.onLoadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                rowsBeanList.clear();
                homeHotList.clear();
                homeList.clear();
                initData();
                //   presenter.onRefresh();
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.more_hot:
                Bundle bundle = new Bundle();
                bundle.putInt("hotDataId", hotDataId);
                go(PopularWorksActivity.class, bundle);
                break;
            case R.id.user_info:
                go(PersonalActivity.class);
                break;
            case R.id.phoenix_cademy_rl:
                go(ActivityBrowser.class);
                break;
        }

    }
}
